import { TOGGLE_COLLECT, SET_COLLECT_CHECK, SET_ALL_COLLECT_CHECK, DEL_CHECK_COLLECT } from '../types'
import { getStore, setStore, removeStore } from '@/utils/mUtils'

const MY_COLLECT_LIST = 'MY_COLLECT_LIST'
const state = {
	allChecked: false,
	collectList: getStore(MY_COLLECT_LIST)?JSON.parse(getStore(MY_COLLECT_LIST)):[]
}

const getters = {
	collectList: state => {
		return state.collectList
	},
	allCheckStatus: state => {
		return state.allChecked
	},
	collectLen: state => {
		return state.collectList.length
	}
}

const actions = {
	toggleCollect ({commit}, data) {
		commit(TOGGLE_COLLECT, data)
	},
	checked ({commit}, data) {
		commit(SET_COLLECT_CHECK, data)
	},
	allCheck ({commit}, data) {
		commit(SET_ALL_COLLECT_CHECK, data)
	},
	delCheck ({commit}) {
		commit(DEL_CHECK_COLLECT)
	}
}

const mutations = {
	[TOGGLE_COLLECT] (state, data) {
		let id = data.goodsId ? data.goodsId : data._id
		let item = state.collectList.find(n=>n._id == id)
		// 判断是否已有，有则添加到本地，没有则删除
		if (!item) {
			state.collectList.push({
				_id: id,
				goodsName: data.goodsName,
				goodsCover: data.goodsCover,
				price: data.price,
				check: false
			})
		}else {
			state.collectList.forEach((n, i) => {
				if (n._id == id) {
					state.collectList.splice(i, 1)
				}
			})
		}
		setStore(MY_COLLECT_LIST, JSON.stringify(state.collectList))
	},
	[SET_COLLECT_CHECK] (state, data) {
		data.check = !data.check
	},
	[SET_ALL_COLLECT_CHECK] (state, data) {
		state.allChecked = !state.allChecked
		data.forEach(n => {
			if (state.allChecked) {
				n.check = true
			}else {
				n.check = false
			}
		})
	},
	[DEL_CHECK_COLLECT] (state) {
		let arr = []
		state.collectList.forEach((n, i) => {
			if (!n.check) {
				arr.push(n)
			}
		})
		state.collectList = arr
		setStore(MY_COLLECT_LIST, JSON.stringify(state.collectList))
	}
}

export default {
	state,
	getters,
 	mutations,
 	actions
}